<template>
  <div class="loginPage">
    <el-form :model="form" status-icon :rules="rules" ref="form" label-width="100px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.userName" autocomplete="on"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="checkPass">
        <el-input type="password" v-model="form.password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">提交</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {mapActions} from "vuex";
import {getJson, postJson} from "@/api/http";
import {User_getCurrentUserInfo, User_login} from "@/api/api";
import {admin} from "@/index";
import CryptoJS from 'crypto-js';

export default {
  name: "LoginComponent",
  data() {
    return {
      form: {
        userName: "admin",
        password: 'admin',
      },
      rules: {},
    }
  },
  methods: {
    ...mapActions('user', [
      'xUserToken',
      'xUser',]), // 映射 user 模块的 login action
    async login() {
      const hashedPassword = CryptoJS.SHA256(this.form.password).toString();

      let data = {
        userName: this.form.userName,
        password: hashedPassword,
      }
      let res = await postJson(User_login, data)
      await this.xUserToken(res.data)
      if (res.code === 1) {
        let userInfoR = await getJson(User_getCurrentUserInfo, {})
        await this.xUser(userInfoR.data)
        await this.$router.push(admin); // 登录成功后跳转到dashboard或其他页面
      }
    },
    logout() {
      this.$store.dispatch('logout');
    }
  }
}
</script>

<style scoped>
.loginPage{
    margin: auto;
}

</style>